package com.haiyou.swagger.config;

import com.github.xiaoymin.swaggerbootstrapui.annotations.EnableSwaggerBootstrapUI;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.haiyou.swagger.properties.SwaggerProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;

import static com.google.common.base.Predicates.not;
import static springfox.documentation.builders.PathSelectors.regex;

/**
 * 自动配置
 */
@EnableSwagger2
@Configuration
@EnableConfigurationProperties(value = SwaggerProperties.class)
@Slf4j
@EnableSwaggerBootstrapUI
public class SwaggerAutoConfiguration extends WebMvcConfigurerAdapter {

    @Autowired
    private SwaggerProperties swaggerProperties;

    @Bean
    public Docket createRestApi() {

        log.info("swaggerProperties配置：{}", swaggerProperties);

        List<Parameter> pars = new ArrayList<>();

        if (swaggerProperties.isShowToken()) {
            ParameterBuilder ticketPar = new ParameterBuilder();
            ticketPar.name("token").description("user token").defaultValue(swaggerProperties.getDefaultValue())
                    .modelRef(new ModelRef("string")).parameterType("header")
                    //header中的ticket参数非必填，传空也可以
                    .required(false).build();

            //根据每个方法名也知道当前方法在设置什么参数
            pars.add(ticketPar.build());
        }


        return new Docket(DocumentationType.SWAGGER_2)
                .enable(swaggerProperties.isEnable())
                .globalOperationParameters(pars)
                .apiInfo(apiInfo())
                .select()
                .apis(basePackage(swaggerProperties.getWebBasePackage()))
//                .apis(RequestHandlerSelectors.basePackage(swaggerProperties.getWebBasePackage()))
                .paths(not(regex("/error.*")))
                .build();
    }

    public static Predicate<RequestHandler> basePackage(final String basePackage) {
        return input -> declaringClass(input).transform(handlerPackage(basePackage)).or(true);
    }

    /**
     * 处理包路径配置规则,支持多路径扫描匹配以逗号隔开
     *
     * @param basePackage 扫描包路径
     * @return Function
     */
    private static Function<Class<?>, Boolean> handlerPackage(final String basePackage) {
        return input -> {
            for (String strPackage : basePackage.split(",")) {
                boolean isMatch = input.getPackage().getName().startsWith(strPackage);
                if (isMatch) {
                    return true;
                }
            }
            return false;
        };
    }

    /**
     * @param input RequestHandler
     * @return Optional
     */
    private static Optional<? extends Class<?>> declaringClass(RequestHandler input) {
        return Optional.fromNullable(input.declaringClass());
    }

    private ApiInfo apiInfo() {
        String author = swaggerProperties.getAuthor();
        String url = swaggerProperties.getUrl();
        String version = swaggerProperties.getVersion();
        String email = swaggerProperties.getEmail();
        return new ApiInfoBuilder()
                .title(swaggerProperties.getTitle())
                .version(version)
                .description(swaggerProperties.getDescription())
                .contact(new Contact(author, url, email))
                .build();
    }

    @Bean
    public WebMvcConfigurerAdapter forwardToIndex() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addViewControllers(ViewControllerRegistry registry) {
                if (swaggerProperties.isRedirect()) {
                    registry.addViewController("/").setViewName("redirect:/swagger-ui.html");
                }
            }
        };
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        if (!swaggerProperties.isEnable()) {
            return;
        }
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");

        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}
